<template>
  <el-dialog v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`新增子分类`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <!-- 大类名称 -->
      <el-form-item label="大类名称" prop="categoryName">
        <el-input v-model="drawerProps.row.categoryName" placeholder="请输入大类名称" clearable />
      </el-form-item>
      <!-- 大类编号 -->
      <el-form-item label="分类编号" prop="category">
        <el-input v-model="drawerProps.row.category" placeholder="请输入分类编号" clearable />
      </el-form-item>
      <!-- 子类名称 -->
      <el-form-item label="子类名称" prop="typeName">
        <el-input v-model="drawerProps.row.typeName" placeholder="请输入子类名称 " />
      </el-form-item>
      <!-- 关键词 -->
      <el-form-item label="关键词" prop="keywords">
        <el-select
          v-model="drawerProps.row.keywords"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请输入关键词，回车确认"
        >
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Clothes } from "@/api/interface";

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Clothes.CategoryStat>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};
const rules = reactive({
  typeName: [{ required: true, message: "请输入子类名称", trigger: "blur" }]
});
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    const params = {
      id: drawerProps.value.row.id,
      category: drawerProps.value.row.category,
      keywords: drawerProps.value.row.keywords,
      typeName: drawerProps.value.row.typeName
    };
    console.log("params", params);
    try {
      await drawerProps.value.api!(params);
      ElMessage.success({ message: `新增子类成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
